# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :sendEmail.py
# @Time      :2022/7/14 0:26
# @Author    :jiaxuesong
import smtplib
import time, os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

#定义一个发送邮件的类
class SendEmail(object):
    #定义初始化方法
    def __init__(self):
        # 配置邮箱属性
        # 发送邮箱
        self.sender = '1033353613@qq.com'
        #配置接收邮箱
        self.reciver = ['1033353613@qq.com', '979034018@qq.com']
        #配置邮件发送主题
        t = time.strftime('%Y_%m_%d_%H_%M_%S',time.localtime())
        self.title = '自动化测试结果' + t
        #发送服务器
        self.smtpservr = 'smtp.qq.com'
        #发送邮箱用户名及密码
        self.username = '1033353613@qq.com'
        self.password = 'kptqxaqnhsmpbdjc'

    def email_content(self, file):
        # 组装邮件内容和标题
        # 获取测试报告目录
        # 获取目录下所有html内容
        # 组装邮件内容和标题
        # 添加附件内容
        # 添加文件的文本内容
        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            #添加附件内容
            att = MIMEText(mail_body, 'plain', 'utf-8')
            att['Content_type'] = 'application/octet-stream'
            att['Content-Disposition'] = 'attachment; filename=report.html'
            self.msg.attach(att)
            # 添加邮件的文本内容
            content = '自动化测试报告详情，请查收附件'
            self.msg.attach(MIMEText(content, 'plain', 'utf-8'))
            self.msg['Subject'] = Header(self.title, 'utf-8')
            self.msg['To'] = ','.join(self.reciver)

    # 登录并发送邮件
    def send_email(self, file):
        self.email_content(file)
        try:
            # 实例化smtp类
            smtp = smtplib.SMTP()
            # 连接smtp服务器
            smtp.connect(self.smtpservr)
            # 登录邮箱
            smtp.login(self.username, self.password)
            # 设置邮箱发件人，接收人，和发件内容
            smtp.sendmail(self.sender, self.reciver, self.msg.as_string())
        except Exception as msg:
            print(f'邮件发送失败：{msg}')
        else:
            print('邮件发送成功')
        finally:
            smtp.quit()

